package com.example.myapplication1;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

public class CalculateActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculate2);

        TextView currencyNameTv = findViewById(R.id.currencyName);
        EditText amountEt = findViewById(R.id.amount);
        TextView resultTv = findViewById(R.id.result);

        String currencyName = getIntent().getStringExtra("currencyName");
        currencyNameTv.setText(currencyName);
        amountEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                calculate(amountEt, resultTv);
            }
        });
    }

    private void calculate(EditText amountEt, TextView resultTv) {
        try {
            String amountStr = amountEt.getText().toString();
            if (amountStr.isEmpty()) {
                resultTv.setVisibility(View.INVISIBLE);
                return;
            }

            float amount = Float.parseFloat(amountStr);
            float rate = Float.parseFloat(getIntent().getStringExtra("price"));
            float result = amount / rate;

            resultTv.setVisibility(View.VISIBLE);
            resultTv.setText(String.format(Locale.getDefault(), "%.2f", result));
        } catch (NumberFormatException e) {
            resultTv.setVisibility(View.VISIBLE);
            resultTv.setText("Invalid input");
        }
    }
}